//index.js
//获取应用实例
const app = getApp()
var bmap = require('../../libs/bmap-wx.js');
//const sortData = require('../../utils/sortIndexData.js');
import Api from '../../utils/api';
import util from '../../utils/util';
import { WebSocket } from '../../utils/Socket'
//let timerClear = null;
var BMap;
// var timer;
var indexHideFlag = false;

Page({
  data: {
    timer:null,
    timerClear: null,
    advertisement: '', //存放广告信息
    bannerCurrentIndex: 0,
    motto: 'Hello World',
    userInfo: {},
    sortIndex: 0, //分类第一层
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    sortALL: [],
    sortList: [],
    scrollHeight: wx.getSystemInfoSync().windowHeight,
    isGoTop: false, //是否需要显示返回顶部按钮
    city: "", //获取当前城市地址
    isNoCity: false, //没有获取城市地址时  授权返回后 接口数据需要再onshow中执行
    bannerList: [], //首页轮播数据
    spellList: [], //拼团接口数据
    spikeList: [], //秒杀数据
    selectedList: [], //精选列表数据
    hotDataList: [], //查询促销标签以及其店铺数据
    shopList: [], //更多商品
    istemplate: false, //是否显示商家数据
    page: 1,
    size: 10,
    totalPages: 0,
    refreshFlag: false,
    formIdString: '',
    countDownNum: '',

    isPrize: null,
    id: '',
    ty: '', //扫码进来接收到type
    shopShareRecordId: '', //记录id

    imagewidth: '',
    imageheight: '',
  },

  onLoad: function() {
    console.log('index====onLoad()')
    let _this = this;
    
    // 创建连接websocket
    let socket = new WebSocket();
    socket.bulidConnectAndMonitor(
      {},
      'wss://yps.yikesong.cc/wxServer',
      '/topic/wx/push/all',
      function (body) {
        //接收广播频道
        console.log(body);
      },
      function (con) {
        console.log(con);
        //添加一对一频道
        socket.addMessageMonitor("/user/123456/wx/push/singleton", function (body) {
          console.log(body);
        });
      }
    );

    console.log(wx.getStorageSync('originalData'), '============')
    //查询首页数据
    if (!wx.getStorageSync('originalData')) {
      // _this.getLocationAgain()
      _this.setData({
        isNoCity: true,
      });
      _this.getLocation();
    } else {
      console.log('0999')
      _this.setData({
        city: wx.getStorageSync('originalData').addressComponent.city
      })
      _this.allLoadData();
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    console.log('命周期函数--监听页面初次渲染完成')
    //
  },
  imageLoad: function(e) {
    console.log(e)
    var imageSize = util.imageUtil(e)
    this.setData({
      imagewidth: imageSize.imageWidth,
      imageheight: imageSize.imageHeight,
    })
    this.countDown();

  },
  onShow: function() {
    console.log('onShow come in')
    let _this = this;
    var thirdSession = wx.getStorageSync('third_Session');

    if (indexHideFlag && _this.data.city == wx.getStorageSync('originalData').addressComponent.city) {
      _this.searchSpike(); //首页的秒杀
      indexHideFlag = false;
    }
    _this.setData({
      refreshFlag: false
    })
    //查询线上显示标记

    //后台进前台，再进入首页时调用后台接口
    console.log(app.globalData.indexRequestFlag, app.globalData.otherPageHideFlag)
    if (app.globalData.indexRequestFlag && !app.globalData.otherPageHideFlag && thirdSession) {
      var cityFlag = wx.getStorageSync('originalData').addressComponent.city;
      console.log(cityFlag, '=============')
      if (cityFlag) {
        _this.popAds(cityFlag);

      }
      app.globalData.indexRequestFlag = false;
    } else {
      wx.showTabBar({})
    }
    app.globalData.otherPageHideFlag = false;

    //查询线上页面元素显示标记
    _this.isProductRelease();
    //判断城市
    if (_this.data.isNoCity) {
      if (!wx.getStorageSync('originalData')) {
        _this.getLocationAgain()
      } else {
        _this.setData({
          city: wx.getStorageSync('originalData').addressComponent.city,
          isNoCity: false,
        })
        // _this.allLoadData()
      }
    } else {
      if (_this.data.city != "" && _this.data.city != wx.getStorageSync('originalData').addressComponent.city) {
        console.log('里面的信息')
        _this.setData({
          city: wx.getStorageSync('originalData').addressComponent.city
        })
        var cityFlag = wx.getStorageSync('originalData').addressComponent.city;
        if (cityFlag && thirdSession) {
          _this.popAds(cityFlag);
        }
        _this.allLoadData()
        console.log('isNoCity:' + _this.data.isNoCity, wx.getStorageSync('originalData').addressComponent.city);
      }
    }
    //加载购物车数量
    if (app.globalData.loginFlag && !app.globalData.shoppingDataLength) {
      app.loadCartNum();
    }

  },

  // 调广告接口
  popAds: function(cityFlag) {
    var _this = this;
    Api.popAds(cityFlag).then(res => {
      console.log(res.data, '调广告接口success');
      var advertisement = res.data;
      console.log(typeof(advertisement), '=====advertisement')
      if (advertisement.id) {
        _this.setData({
          advertisement: advertisement,
        })
        wx.hideTabBar({})
      }
    })
  },
  //5秒定时器
  countDown: function() {
    let that = this;
    let countDownNum = 5; //获取倒计时初始值 
    that.setData({
      countDownNum: countDownNum
    })
    // that.setData({
   var timer = setInterval(function() {
      countDownNum--;
      console.log(countDownNum);
      that.setData({
        countDownNum: countDownNum
      })
      if (countDownNum <= 0) {
        if (that.data.timer) {
          clearInterval(that.data.timer);
          // that.data.timer = null;
          that.setData({
            timer:null
          })
        }
        that.setData({
          advertisement: ''
        })
        wx.showTabBar({})
      }
    }, 1000)
    that.setData({
      timer:timer
    })
    // })
  },
  // 关闭广告事件
  closeAds: function() {
    var that = this;
    that.setData({
      advertisement: '',
    })
    clearInterval(that.data.timer);
    // 显示tab页
    wx.showTabBar({})
  },
  // 点击广告进入店铺
  joinAds: function(e) {
    var that = this;
    var advertisementId = e.currentTarget.dataset.id;
    var jumpPath = that.data.advertisement.jumpPath;
    console.log(jumpPath, '========跳转路径')
    if (jumpPath) {
      Api.clickAds(advertisementId).then(res => {
        console.log(res, '调点击广告success');
        if (that.data.advertisement.shopId) {
          wx.navigateTo({
            url: jumpPath,
          })
          wx.showTabBar({})
        }
      })
    }
    // else{
    //   wx.navigateTo({
    //     url:'/pages/details/shopDetail?id=1167012241522954240',
    //   })
    // }

  },
  // 
  onUnload: function() {
    console.log('index====onUnload')
    // wx.clearStorage();
    // wx.clearStorageSync();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    //console.log("上拉刷新")
    if (!this.data.refreshFlag) {
      let _this = this;
      _this.setData({
        page: 1,
        shopList: [],
        refreshFlag: true
      })
      wx.showNavigationBarLoading();
      clearInterval(_this.data.timerClear);
      _this.moreShop(function() {
        _this.allLoadData();
        // 取消标题栏进度条效果
        setTimeout(function() {
          wx.hideNavigationBarLoading();
          wx.stopPullDownRefresh();
          _this.setData({
            refreshFlag: false
          })
        }, 2000);
      });
    } else {
      console.log('频繁刷新中');
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    //console.log("下拉加载")
    let _this = this;
    if (_this.data.page < _this.data.totalPages) {
      _this.setData({
        page: _this.data.page + 1,
      })
      wx.showLoading({
        title: '加载中',
      })
      _this.moreShop(function() {
        setTimeout(function() {
          wx.hideLoading()
        }, 1000)
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    app.globalData.otherPageHideFlag = true;
  },

  //首页刚进来需要加载接口集合
  allLoadData() {

    this.setData({
      page: 1,
      shopList: [],
      bannerList: [], //首页轮播数据
      spellList: [], //拼团接口数据
      spikeList: [], //秒杀数据
      selectedList: [], //精选列表数据
      hotDataList: [], //查询促销标签以及其店铺数据
      shopList: [], //更多商品
    })
    let _this = this;
    _this.loadIndexBanner(); //首页的轮播
    _this.loadIndexSort(); //首页的分类
    _this.searchSpell(); //首页的拼团
    _this.searchSpike(); //首页的秒杀
    _this.selectedData(); //首页的精选店铺
    _this.getHotData(); //查询促销标签以及其店铺
    _this.moreShop(); //更多商品
  },

  getUserInfo: function(e) {

  },

  //取消了获取地理后 重新开启授权地理位置
  getLocationAgain() {
    console.log('重新开启授权地理位置')
    let _this = this;
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: function(res) {
        console.log("我的定位权限", res)
      },
      fail: function(res) {
        wx.getSetting({
          success: function(res) {
            console.log(res)
            if (!res.authSetting['scope.userLocation']) {
              wx.showModal({
                title: '',
                content: '请允许惠生活获取您的定位！',
                confirmText: '授权',
                success: function(res) {
                  if (res.confirm) {
                    console.log(2222)
                    wx.openSetting({
                      success: function(res) {
                        console.log(res)
                        _this.getLocation();
                      },
                      fail: function(res) {
                        // _this.onLoad();
                      }
                    })
                  } else {
                    console.log('get location fail');
                    wx.showToast({
                      title: '您取消授权！请退出应用！',
                      icon: 'none',
                      duration: 2000,
                    })
                  }
                }
              })
            } else {
              //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
              wx.showModal({
                title: '',
                content: '请在系统设置中打开定位服务',
                confirmText: '确定',
                success: function(res) {
                  _this.getLocation();
                }
              })
            }
          }
        })
      }
    })
  },
  //页面隐藏
  onHide() {
    indexHideFlag = true;
    console.log('====onhide()')
    var that = this;
    if (that.data.timer) {
      clearInterval(that.data.timer);
      // timer = null;
      that.setData({
        timer:null
      })
    }
    that.setData({
      advertisement: ''
    })
    if (that.data.refreshFlag) {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      that.setData({
        refreshFlag: false
      });
    }
    if (that.data.timerClear) {
      clearInterval(that.data.timerClear);
      that.setData({
        timerClear:null
      })
    }

  },
  //分类滑动切换
  touchStart(e) {

  },
  touchChange() {

  },
  touchEnd() {

  },

  //返回顶部
  goTop() {
    let _this = this;
    // _this.setData({
    // scrollTop: 0,
    // })
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  ////监听页面滚动,判断是否出现返回顶部图标
  onPageScroll: function(e) {
    let _this = this;
    // let scrollTop = e.detail.scrollTop;
    let scrollTop = e.scrollTop;
    if (scrollTop < _this.data.scrollHeight / 2) {
      _this.setData({
        isGoTop: false
      })
    } else {
      _this.setData({
        isGoTop: true
      })
    }
  },
  //轮播图数据
  loadIndexBanner() {
    let _this = this;
    console.log("sss", _this.data.city)
    Api.loadIndexBanner({
      "city": _this.data.city
    }).then(res => {
      console.log("轮播图数据", res)
      _this.setData({
        bannerList: res.data
      })
      _this.setData({
        bannerCurrentIndex: 0,
      });
    })
  },

  //获取首页分类栏目信息
  loadIndexSort() {
    let _this = this;
    let data = {
      "city": _this.data.city,
      "delFlag": false, //默认false
    }
    //console.log(data)
    Api.loadIndexSort(data).then(res => {
      var sortList = [];
      console.log(res)
      for (var i = 0, len = res.data.length; i < len; i += 10) {
        sortList.push(res.data.slice(i, i + 10));
      }

      _this.setData({
        sortList: sortList,
        sortALL: res.data
      })

    })
  },

  //获取拼团信息	"spellType":"GROUP"
  searchSpell() {
    let _this = this;
    let data = {
      "cityName": _this.data.city,
      "spellType": "GROUP" //拼团的类型
    }
    Api.searchSpell(1, 5, data).then(res => {
      console.log("拼团信息", res)
      _this.setData({
        spellList: res.data.dataList
      })
    })
  },

  //获取秒杀信息	"spellType":"LIMITED_TIME"
  searchSpike() {
    //清除定时器
    let _this = this;
    let data = {
      "cityName": _this.data.city,
      "spellType": "LIMITED_TIME" //秒杀的类型
    }
    console.log('searchSpike', data);
    Api.searchSpell(1, 5, data).then(res => {
      console.log('searchSpikeList', res.data.dataList.length);

      if (res.data.dataList.length > 0) {
        var timerClear = setInterval(function() {
          res.data.dataList.forEach((item, index, arr) => {
            if (util.getTimeLeft(item.endTime) < 0) {
              let dataTime = {
                days: "00",
                hours: "00",
                minutes: "00",
                seconds: "00"
              }
              arr[index].mssTime = dataTime;
              clearInterval(_this.data.timerClear);
              arr.splice(index, 1)
              _this.setData({
                spikeList: arr
              })
              _this.searchSpike();
              return;
            } else {
              arr[index].mssTime = util.getTimeLeft(item.endTime)
              _this.setData({
                spikeList: arr
              })
            }
          })
        }, 1000)
        _this.setData({
          timerClear: timerClear
        });
        // console.log(timerClear)
      }
    })
  },


  //精选店铺
  selectedData() {
    let _this = this;
    Api.selectedData({
      city: _this.data.city
    }).then(res => {
      console.log("精选店铺", res)
      let list = res.data;
      // _this.setData({
      //   selectedList: res.data
      // })
      let len = 12 - list.length;
      let item = {
        trademarkImage: "/img/no-shop-img.png",
        shopName: "暂无商品",
        introduction: "无",
        isUrl: true,
      }
      for (let i = 0; i < len; i++) {
        list.push(item)
      }
      _this.setData({
        selectedList: list
      })
    })
  },


  //查询促销标签以及其店铺
  getHotData() {
    let _this = this;
    Api.getHotData({
      city: _this.data.city
    }).then(res => {
      //console.log("查询促销标签以及其店铺", res)
      let list = res.data;
      list.forEach(function(item, index, arr) {
        let len = 6 - item.retailShops.length;
        let itemShop = {
          trademarkImage: "/img/no-shop-img.png",
          shopName: "暂无商品",
          introduction: "无",
          isUrl: true,
        }
        for (let i = 0; i < len; i++) {
          item.retailShops.push(itemShop);
        }
      })
      //console.log(list[0].retailShops)
      _this.setData({
        hotDataList: list
      })
    })
  },

  //分类列表跳转分类页面
  goSort(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    wx.reLaunch({
      url: `/pages/sort/sort?index=${index}`
    })
  },
  //查看更多商品
  moreShop(callback) {
    let _this = this;
    Api.moreShop(_this.data.page, _this.data.size, _this.data.city).then(res => {
      console.log("查看更多商品", res)
      _this.setData({
        shopList: _this.data.shopList.concat(res.data.dataList),
        totalPages: res.data.totalPages
      });
      (callback && (typeof callback) === "function") && callback();
    }).catch(err => {
      _this.setData({
        refreshFlag: false
      })
    });
  },
  //判断产品发布信息
  isProductRelease() {
    let _this = this;
    Api.isProductRelease().then(res => {
      console.log('进入标记查询', res)
      _this.setData({
        istemplate: res.data
      })
    }).catch(err => {
      _this.setData({
        istemplate: true
      })
    });
  },
  /**
   * 获取百度的地理位置
   * 
   */
  getLocation() {
    let _this = this;
    BMap = new bmap.BMapWX({
      ak: 'iOYBmDKHicYmzZigGIGnurrPf1YMKlEj'
    });
    BMap.regeocoding({
      success: function(res) {
        console.log("地理:", res)
        let city = res.originalData.result;
        //获取开通城市
        Api.searchOpenCity().then(res => {
          console.log(res, "获取开通城市列表")
          let data = res.data;
          for (let i = 0; i < data.length; i++) {
            if (city) {
              console.log(city.addressComponent.city)
              if (data[i] == city.addressComponent.city) {
                wx.setStorageSync('originalData', city);
                //请求数据
                _this.setData({
                  city: city.addressComponent.city
                })
                _this.allLoadData();
                return;
              }
            }
          }
          let resultCity = {
            addressComponent: {
              adcode: "340111",
              city: "合肥市",
              city_level: 2,
              country: "中国",
              country_code: 0,
              country_code_iso: "CHN",
              country_code_iso2: "CN",
              direction: "南",
              distance: "65",
              district: "包河区",
              province: "安徽省",
              street: "包河大道",
              street_number: "118号-3楼",
              town: ""
            },
            location: {
              lat: 31.793219451417567,
              lng: 117.30794046911323
            }
          }
          wx.showToast({
            title: '您所在的城市' + city.addressComponent.city+'不是开通城市,默认设置您的位置为合肥市',
            icon: 'none',
            image: '',
            duration: 2000,
            mask: true,
          })
          wx.setStorageSync('originalData', resultCity);
          //请求数据
          _this.setData({
            city: resultCity.addressComponent.city
          })
          _this.allLoadData()
        })
      },
      fail: function(res) {
        console.log("请求百度失败,默认定位合肥", res);
        let resultCity = {
          addressComponent: {
            adcode: "340111",
            city: "合肥市",
            city_level: 2,
            country: "中国",
            country_code: 0,
            country_code_iso: "CHN",
            country_code_iso2: "CN",
            direction: "南",
            distance: "65",
            district: "包河区",
            province: "安徽省",
            street: "包河大道",
            street_number: "118号-3楼",
            town: ""
          },
          location: {
            lat: 31.793219451417567,
            lng: 117.30794046911323
          }
        }
        wx.setStorageSync('originalData', resultCity);
        //请求数据
        _this.setData({
          city: resultCity.addressComponent.city
        })
        _this.allLoadData();
      },
    });
  },
})